package com.example.shop_2305.fg

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.entity.Cart
import com.example.lib_base.mvvm.BaseFragment
import com.example.lib_base.param.OrderDetail
import com.example.lib_base.param.PPreOrder
import com.example.shop_2305.R
import com.example.shop_2305.adapter.CartAdapter
import com.example.shop_2305.databinding.FragmentCartBinding


class CartFragment : BaseFragment<FragmentCartBinding, CartViewModel>() {
    lateinit var cartAdapter: CartAdapter
    override fun initView() {
        cartAdapter = CartAdapter()
        binding.rvCart.adapter = cartAdapter
        binding.rvCart.layoutManager = LinearLayoutManager(context)

        viewModel.cart("true", "10", "1")
        //点击item上的三个控件 均可以控制底部金额的变化
        cartAdapter.addChildClickViewIds(R.id.cart_cb, R.id.cart_add, R.id.cart_sub)
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.cart_cb -> {
                    //页面上 选中状态 发生了变化  adapter.data 发生了变化  接口  没有变化
                    cartAdapter.data[position].isChecked = !cartAdapter.data[position].isChecked
                }

                R.id.cart_add -> {
                    cartAdapter.data[position].cartNum++
                    (cartAdapter.getViewByPosition(position, R.id.cart_num) as TextView).text =
                        cartAdapter.data[position].cartNum.toString()
                    (cartAdapter.getViewByPosition(position, R.id.cart_sub) as TextView).isEnabled =
                        true
                    //接口调用
                    viewModel.cartUpdate(
                        cartAdapter.data[position].id,
                        cartAdapter.data[position].cartNum
                    )
                }

                R.id.cart_sub -> {
                    cartAdapter.data[position].cartNum--
                    (cartAdapter.getViewByPosition(position, R.id.cart_num) as TextView).text =
                        cartAdapter.data[position].cartNum.toString()
                    if (cartAdapter.data[position].cartNum == 1) {
                        (cartAdapter.getViewByPosition(
                            position,
                            R.id.cart_sub
                        ) as TextView).isEnabled = false
                    }
                    //接口调用
                    viewModel.cartUpdate(
                        cartAdapter.data[position].id,
                        cartAdapter.data[position].cartNum
                    )
                }
            }
            checkAmount()//计算底部金额和选中状态
        }
        binding.cb.setOnCheckedChangeListener { buttonView, isChecked ->
            //点击cb，rv的选中状态发生变化  同时金额也发生变化
            binding.cb.setOnClickListener {
                cartAdapter.data.forEach {
                    it.isChecked = isChecked
                }
                cartAdapter.notifyDataSetChanged()
                checkAmount()
            }
        }
        //点击管理  文字变成 “取消” 同时 底部 金额和立即下单按钮消失  显示  收藏和删除  再次点击恢复原来的状态
        binding.tvManage.setOnClickListener {
            if (binding.tvManage.text.toString() == "管理") {
                binding.tvManage.text = "取消"
                binding.llManage.isVisible = false
                binding.llCancel.isVisible = true
            } else {
                binding.tvManage.text = "管理"
                binding.llManage.isVisible = true
                binding.llCancel.isVisible = false
            }
        }
        //点击管理，判断是否有选中的商品，有选中的进行删除
        binding.tvDelete.setOnClickListener {
            var count = 0//最后显示选中几个
            cartAdapter.data.forEach {
                if (it.isChecked) {
                    count++
                }
            }
            //判断数量
            if (count > 0) {
                var ids = arrayOf<Int>()
                var carts = mutableListOf<Cart>()
                cartAdapter.data.forEach {
                    if (it.isChecked) {
                        ids += it.id
                        carts.add(it)
                    }
                }
                viewModel.cartDelete(ids)
                //刷新页面数据（方式一：重新请求数据  但注意修改底部选中数量和金额  方式二：使用adapter.remove）
                //使用方法二演示
                cartAdapter.data.removeAll(carts)
                cartAdapter.notifyDataSetChanged()
                checkAmount()
            } else {
                ToastUtils.showLong("请至少选择一个商品")
            }
        }
        //点击提交订单，进行预下单接口调用   调用成功  跳转加载预下载界面
        binding.tvOrdernow.setOnClickListener {
            val size = cartAdapter.data.filter { it.isChecked }.size
            if (size > 0) {
                var list = mutableListOf<OrderDetail>()//接收所有的要购买的商品信息 可能是多个  可能是一个
                cartAdapter.data.filter { it.isChecked }
                    .forEach {
                        val orderDetail = OrderDetail()
                        orderDetail.shoppingCartId = it.id//添加对应的购物车id
                        list.add(orderDetail)
                    }
                var pPreOrder = PPreOrder()
                pPreOrder.preOrderType = "shoppingCart" //设置合适的购买方式
                pPreOrder.orderDetails = list//具体添加的购物车的id们  //将选中的所有的商品信息数据保存到实体类中
                viewModel.preOrder(pPreOrder)
            } else {
                ToastUtils.showLong("请至少选择一个商品")
            }

        }
    }

    private fun checkAmount() {
        var total = 0f//最后显示的合计金额
        var count = 0//记录最后选中了几个
        cartAdapter.data.forEach {
            if (it.isChecked) {
                total += it.cartNum * it.price.toFloat()
                count++
            }
        }
        binding.tvAmount.text = "合计:$total"
        binding.tvCount.text = "购物车(${cartAdapter.data.size})"
        //怎么判断是否全选
        if (count == cartAdapter.data.size && count > 0) {
            binding.cb.isChecked = true
            binding.cb.text = "全选($count)"
        } else {
            binding.cb.isChecked = false
            binding.cb.text = "全选($count)"
        }
    }

    override fun initData() {
        viewModel.cartSuccess.observe(this) {
            if (it.code == 200) {
                cartAdapter.data.clear()
                cartAdapter.data.addAll(it.data.list)
                cartAdapter.notifyDataSetChanged()
                binding.tvCount.text = "购物车(${cartAdapter.data.size})"
            } else {
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.cartFail.observe(this) {
            ToastUtils.showLong(it)
        }
        viewModel.updateSuccess.observe(this) {
            ToastUtils.showLong(it.message)
        }
        viewModel.updateFail.observe(this) {
            ToastUtils.showLong(it)
        }
        viewModel.deleteSuccess.observe(this) {
            ToastUtils.showLong(it.message)
        }
        viewModel.preOrderSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                ARouter.getInstance().build("/app/CreateOrderActivity")
                    .withString("preOrderNo", it.data.preOrderNo).navigation()
            }
        }
    }

    override fun getViewModel(): Class<CartViewModel> = CartViewModel::class.java

    override fun getLayout(): Int = R.layout.fragment_cart

}